import React, { useState, useEffect } from 'react';

interface Question {
  id?: number;
  title: string;
  content: string;
  type: string;
  options?: string[];
  answer: string;
  lang?: string;
}

interface Props {
  open: boolean;
  question?: Question | null;
  onClose: () => void;
  onSave: (q: Question) => void;
}

const defaultQuestion: Question = {
  title: '',
  content: '',
  type: '单选题', // 默认就是单选题，保证有答案表单
  options: [],
  answer: '',
};

const QuestionEditModal: React.FC<Props> = ({ open, question, onClose, onSave }) => {
  const [form, setForm] = useState<Question>(defaultQuestion);
  const [charCount, setCharCount] = useState(0);

  useEffect(() => {
    if (question) setForm(question);
    else setForm(defaultQuestion);
    setCharCount(question?.content?.length || 0);
  }, [question, open]);

  const handleOptionChange = (idx: number, value: string) => {
    const opts = form.options ? [...form.options] : ['', '', '', ''];
    opts[idx] = value;
    setForm({ ...form, options: opts });
  };

  const handleAnswerChange = (val: string) => {
    setForm({ ...form, answer: val });
  };

  if (!open) return null;

  return (
    <div className="modal-mask">
      <div className="modal" style={{ minWidth: 600 }}>
        <h2 style={{ fontSize: 18, marginBottom: 16 }}>{question ? '编辑题目' : '创建题目'}</h2>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
          <label style={{ width: 60 }}>题型：</label>
          <select value={form.type} onChange={e => setForm({ ...form, type: e.target.value })}>
            <option value="单选题">单选题</option>
            <option value="多选题">多选题</option>
            <option value="编程题">编程题</option>
          </select>
          <span style={{ marginLeft: 24 }}>语言：</span>
          <select value={form.lang || 'go语言'} onChange={e => setForm({ ...form, lang: e.target.value })}>
            <option value="go语言">go语言</option>
            <option value="js语言">js语言</option>
          </select>
        </div>
        <div style={{ marginBottom: 16 }}>
          <label style={{ width: 60 }}>标题：</label>
          <input style={{ width: 600 }} value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} placeholder="请输入标题" />
        </div>
        <div style={{ marginBottom: 16 }}>
          <label style={{ width: 60, verticalAlign: 'top' }}>内容：</label>
          <textarea
            style={{ width: 600, height: 120, resize: 'vertical' }}
            value={form.content}
            onChange={e => { setForm({ ...form, content: e.target.value }); setCharCount(e.target.value.length); }}
            placeholder="请输入内容"
          />
          <div style={{ color: '#888', fontSize: 12 }}>字符数：{charCount}</div>
        </div>
        {(form.type === '单选题' || form.type === '多选题') && (
          <>
            {[0, 1, 2, 3].map(i => (
              <div style={{ marginBottom: 8 }} key={i}>
                <label style={{ width: 60, color: '#f5222d' }}>{String.fromCharCode(65 + i)}：</label>
                <input
                  style={{ width: 600 }}
                  value={form.options?.[i] || ''}
                  onChange={e => handleOptionChange(i, e.target.value)}
                  placeholder={`请输入选项内容`}
                />
              </div>
            ))}
            <div style={{ marginBottom: 16 }}>
              <label style={{ width: 60 }}>答案：</label>
              {(form.type === '单选题') ? (
                ['A', 'B', 'C', 'D'].map(v => (
                  <label key={v} style={{ marginRight: 16 }}>
                    <input
                      type="radio"
                      name="answer"
                      checked={form.answer === v}
                      onChange={() => handleAnswerChange(v)}
                    /> {v}
                  </label>
                ))
              ) : (
                ['A', 'B', 'C', 'D'].map(v => (
                  <label key={v} style={{ marginRight: 16 }}>
                    <input
                      type="checkbox"
                      checked={form.answer?.includes(v)}
                      onChange={e => {
                        let ans = form.answer || '';
                        if (e.target.checked) ans += v;
                        else ans = ans.replace(v, '');
                        handleAnswerChange(ans);
                      }}
                    /> {v}
                  </label>
                ))
              )}
            </div>
          </>
        )}
        <div style={{ textAlign: 'right', marginTop: 24 }}>
          <button onClick={onClose}>取消</button>
          <button style={{ marginLeft: 8, background: '#1677ff', color: '#fff', border: 'none', borderRadius: 4, padding: '6px 24px' }} onClick={() => onSave(form)}>确认</button>
        </div>
      </div>
      <style>{`
        .modal-mask { position: fixed; left: 0; top: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.2); z-index: 1000; display: flex; align-items: center; justify-content: center; }
        .modal { background: #fff; border-radius: 8px; padding: 24px; box-shadow: 0 2px 8px #ccc; }
        .modal label { display: inline-block; width: 90px; }
        .modal input, .modal select, .modal textarea { margin-bottom: 8px; }
      `}</style>
    </div>
  );
};

export default QuestionEditModal;